package com.rui.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import com.rui.domain.Academic;
import com.rui.domain.Student;
import com.rui.domain.Teacher;
import com.rui.domain.User;
import com.rui.service.AcademicService;
import com.rui.service.StudentService;
import com.rui.service.TeacherService;
import com.rui.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@Controller
@SuppressWarnings("all")
public class LoginController {

    @Autowired
    private AcademicService academicService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private UserService userService;

    //生成并获取验证码
    @RequestMapping("/getVCode")
    public void getVCode(HttpSession session, HttpServletResponse response) {
        RandomGenerator randomGenerator = new RandomGenerator("123456789QWERTYUPASDFGHJKZXCVBNMqwertyupasdfghjkzxcvbnm", 4);
        //使用hutool工具生成验证码图片
        //ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 100, 4, 3);
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(200, 100);
        //设置验证码背景色
        captcha.setBackground(Color.decode("#eeeeee"));

        captcha.setGenerator(randomGenerator);
        //获取验证码字符串
        String vCode = captcha.getCode();
        System.out.println("验证码："+vCode);
        //将验证码保存到session中
        session.setAttribute("vCode",vCode);
        try(OutputStream os = response.getOutputStream()) {
            //把图片通过输出流写出到页面
            captcha.write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //登录操作
    @RequestMapping("/login.action")
    public String doLogin(String username, String password, String code, HttpSession session, Model model) {

        //从session中获取vCode验证码
        String vCode = (String) session.getAttribute("vCode");
        System.out.println(vCode+":"+code);
        //判断验证码是否正确
        if (!code.equalsIgnoreCase(vCode)) {
            //验证码不正确
            model.addAttribute("username",username);
            model.addAttribute("password",password);
            model.addAttribute("message","验证码错误");
            return "forward:/login.jsp";
        }
        //下面通过username来查找用户信息
        //获取shiro框架的subject对象
        Subject subject = SecurityUtils.getSubject();
        //创建UsernamePasswordToken对象
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try {
            //登录
            subject.login(token);
        }catch (AuthenticationException e) {
            e.printStackTrace();
        }
        //如果返回true，代表认证成功
        boolean b = subject.isAuthenticated();
        if (b) {
            //获取账号的信息
            User user = (User) subject.getPrincipal();
            System.out.println("LoginController>user="+user);
            session.setMaxInactiveInterval(60*60*2);
            //判断账号的身份
            if (user.getRoleId()==1) {
                //查询教务员信息
                Academic academic = academicService.findAcademicByJobNo(user.getUsername());
                session.setAttribute("academic", academic);
                return "redirect:academic/index";
            }else if (user.getRoleId()==2) {
                //查询教师信息
                Teacher teacher = teacherService.findTeacherByJobNo(user.getUsername());
                session.setAttribute("teacher", teacher);
                return "redirect:teacher/index";
            }else if (user.getRoleId()==3) {
                //查询学生信息
                Student student = studentService.findStudentByStuNo(user.getUsername());
                session.setAttribute("student",student);
                return "redirect:student/index";
            }
        }
        model.addAttribute("message", "账号或密码错误");
        return "forward:/login.jsp";
    }

    @RequestMapping("/updatePassword.action")
    @ResponseBody
    public Map<String, Object> updatePassword(String password) {
        Map<String, Object> map = new HashMap<>();
        //通过Subject获取用户信息
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        //使用MD5加密密码
        Md5Hash pwd = new Md5Hash(password, user.getSalt(), 3);
        user.setPassword(pwd.toString());
        boolean b = userService.updatePassword(user);
        if (b) {
            map.put("flag", true);
        } else {
            map.put("flag", false);
        }
        return map;
    }

}
